﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PictrueSimpleSyndication
{
    public class EventTools
    {
        private EventTools() { }

        private static EventTools _EventTools = new EventTools();

        public static EventTools GetInstance()
        {
            return _EventTools;
        }

        private Dictionary<string, List<Action<object>>> Key2CallBack = new Dictionary<string, List<Action<object>>>();

        public void Register(string key, Action<object> func)
        {
            if (!Key2CallBack.ContainsKey(key)) lock (this) if (!Key2CallBack.ContainsKey(key))
                        Key2CallBack[key] = new List<Action<object>>();

            lock (Key2CallBack[key])
                Key2CallBack[key].Add(func);
        }

        public void UnRegister(string key, Action<object> func)
        {
            if (!Key2CallBack.ContainsKey(key))
                return;

            lock (Key2CallBack[key])
            {
                Key2CallBack[key].Remove(func);

                if (Key2CallBack[key].Count == 0)
                    Key2CallBack[key] = null;
            }
        }

        public void TriggerEvent(string key, object obj = null)
        {
            List<Action<object>> list = null;

            if (Key2CallBack.ContainsKey(key)) lock (Key2CallBack[key])
                    list = new List<Action<object>>(Key2CallBack[key]);

            foreach (var item in list ?? new List<Action<object>>())
            {
                item(obj);
            }
        }
    }
}
